import { Logger, MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { LoggerMiddleware } from './web/middleware/logger.middleware';
import { ConfigModule, ConfigService } from '@nestjs/config';
import configuration from './web/config/configuration';
import {
  BootEnv,
  BootProperties,
  DatabaseEnv,
  DatabaseProperties,
} from './web/config/interfaces/configuration';
import { TypeOrmModule } from '@nestjs/typeorm';
import { APP_GUARD } from '@nestjs/core';
import { AuthGuard } from './web/guard/auth.guard';
import { JwtModule } from '@nestjs/jwt';
import { EatyetModule } from './eatyet/eatyet.module';
import { WeatherModule } from './weather/weather.module';

const runOption = {
  env: 'development',
  jwtSecret: '3424324523!$#a',
};

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: ['.env', `.env.${runOption.env}`],
      isGlobal: true,
      load: [configuration],
    }),
    TypeOrmModule.forRootAsync({
      useFactory: (configService: ConfigService) => ({
        type: configService.get<DatabaseProperties>(DatabaseEnv)?.type,
        host: configService.get<DatabaseProperties>(DatabaseEnv)?.host,
        port: configService.get<DatabaseProperties>(DatabaseEnv)?.port,
        username: configService.get<DatabaseProperties>(DatabaseEnv)?.username,
        password: configService.get<DatabaseProperties>(DatabaseEnv)?.password,
        database: configService.get<DatabaseProperties>(DatabaseEnv)?.database,
        autoLoadEntities: true,
        synchronize: true,
      }),
      inject: [ConfigService],
    }),
    JwtModule.register({
      global: true,
      secret: `${runOption.jwtSecret}`,
      signOptions: { expiresIn: '60s' },
    }),
    EatyetModule,
    WeatherModule,
  ],
  providers: [{ provide: APP_GUARD, useClass: AuthGuard }],
})
export class AppModule implements NestModule {
  private readonly logger = new Logger(AppModule.name);

  constructor(private readonly configService: ConfigService) {}

  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('/*');
    this.logger.log(
      `http://127.0.0.1:${this.configService.get<BootProperties>(BootEnv)?.port}`,
    );
  }
}
